import json
import time

from django.core import serializers
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_POST

from cola import control
from cola.common import code, result
from cola.consumers import connected
from cola.models import *
from cola.util.id_worker import worker
from cola.util.logger import logger

loginUser = []
control.init()


# 用户登录和注册
@require_POST
def login(request):
    post_body = json.loads(request.body)
    username = post_body['username']
    name = username.lower()
    if name == 'god' or name == 'tetris' or name == 'siusn':
        # 系统缺省名不允许使用
        return HttpResponse(json.dumps(result.go_back(code.NAME_NOT_ALLOWED, msg='请换一个名字！')))
    try:
        User.objects.get(username=username)
    except User.DoesNotExist:
        User.objects.create(username=username, create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    loginUser.append(username)
    return HttpResponse(json.dumps(result.success(msg='登录成功！')))


# 用户退出
def logout(request, username):
    loginUser.pop(username)
    return HttpResponse(json.dumps(result.success(msg='退出成功！')))


# 区间创建
def space_create(request, space_name, username, size):
    space_list = Space.objects.filter(space_name=space_name)
    for space in space_list:
        if space.status == 1:
            # 区间已存在，未游戏
            if len(space.members) < space.size:
                # 区间未满
                back_data = result.go_back(code.SPACE_EXIST, msg='区间已存在，是否加入？')
            else:
                # 区间已满
                back_data = result.go_back(code.SPACE_FULL, msg='区间已存在，成员已满')
            return HttpResponse(json.dumps(back_data))
        elif space.status == 2:
            # 区间已存在，在游戏中
            return HttpResponse(json.dumps(result.go_back(code.SPACE_INGAME, msg='区间游戏中')))
        elif space.status == 0:
            logger.info("区间已关闭，可以重新创建")
        else:
            logger.error("有异常状态的区间")
    # 没有找到激活状态的区间，则创建新的区间
    id = worker.get_id()
    Space.objects.create(
        id=id,
        space_name=space_name,
        create_user=username,
        create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        size=size,
        status=1,
        members=[{'username': username}]
    )
    return HttpResponse(json.dumps(result.success(data=id, msg='区间创建成功')))


# 区间搜索
def space_search(request, space_name):
    back_data = result.go_back(code.SPACE_NOTEXIST, msg='区间不存在')
    try:
        space_list = Space.objects.filter(space_name=space_name, status=1)
        if space_list.count() > 0:
            back_data = result.success(serializers.serialize('python', space_list, ensure_ascii=False))
    except Space.DoesNotExist:
        pass
    return JsonResponse(back_data, safe=False, json_dumps_params={'ensure_ascii': False})


# 区间加入
def space_join(request, pk, username):
    try:
        space = Space.objects.get(id=pk, status=1)
        if len(space.members) < space.size:
            # 区间未满，可以加入
            member = {'username': username}
            if member in space.members:
                # 列表中存在此用户则不再添加
                pass
            else:
                space.members.append(member)
                space.save()
            back_data = result.success(msg='加入区间成功')
        else:
            back_data = result.go_back(code.SPACE_FULL, msg='区间成员已满，无法加入')
    except Space.DoesNotExist:
        back_data = result.go_back(code.SPACE_NOTEXIST, msg='区间不存在')
    return JsonResponse(back_data)


# 开始游戏
def game_start(request, space_name):
    space = Space.objects.get(space_name=space_name, status=1)
    if space:
        space.status = 2
        space.save()
        group = connected.get(space_name)
        if group and 'users' in group and group['users']:
            user = list(group['users'].values())[0]
            user.start()
        back_data = result.success(msg='游戏开始')
    else:
        back_data = result.go_back(code.SPACE_NOTEXIST, msg='区间不存在')
    return HttpResponse(json.dumps(back_data))


# 保存成绩
@require_POST
def record_save(request):
    post_body = request.body
    sign = post_body['sign']
    Record.objects.update_or_create(post_body, sign=sign)
    return HttpResponse(json.dumps(result.success(msg='保存成绩成功！')))


# 查询成绩
def record_query(request):
    return HttpResponse(json.dumps(result.success(msg='查询成绩成功！')))

